package com.gewu.advertisement.core.service

import com.gewu.advertisement.core.AdvertisementObserver
import com.gewu.advertisement.core.model.Advertising
import com.gewu.advertisement.core.model.GewuPacket
import java.util.concurrent.ConcurrentHashMap

/**
 * 处理服务端下发的消息
 * @author htt 2021/1/7
 */
internal class AdvertisementMsgHandler(
    private val observers: List<AdvertisementObserver>,
    private val observerAdTypes: ConcurrentHashMap<AdvertisementObserver, Array<out Advertising.Type>>
) {

    private val tag = "GewuMsgHandler"

    //广告列表
    private val advertisers = mutableListOf<Advertising>()

    fun handle(packet: GewuPacket<*>) {
        when (packet) {
            is GewuPacket.AdUpdate -> {
                val elements = packet.data
                synchronized(advertisers) {
                    advertisers.clear()
                    advertisers.addAll(elements)
                }
                for (observer in observers) {
                    val adTypes = observerAdTypes[observer] ?: continue
                    val adList = elements.filter { it.adType in adTypes }
                    observer.updateAdvertisements(adList, adTypes, true)
                }
            }
            is GewuPacket.PlayController -> {
                val control = packet.data ?: return
                for (observer in observers) {
                    observer.playControl(control)
                }
            }
            else -> {
            }
        }
    }

    /**
     * 下发广告列表数据到observer
     */
    fun requestAdvertisements(observer: AdvertisementObserver) {
        synchronized(advertisers) {
            val adTypes = observerAdTypes[observer] ?: return
            val adList = advertisers.filter { it.adType in adTypes }
            observer.updateAdvertisements(adList, adTypes, false)
        }
    }

}